<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue'
  const pickerValue = ref('')
  const hierarchyRef = ref()
  const emit = defineEmits(['update:modelValue','change'])
  const props = defineProps({
    placeholder:{
      type:String,
      default: '请选择'
    },
    changeTwoFun:{
      type:Function,
      default:null
    },
    modelValue:{
      type:Array,
      default:[]
    },
    columns:{
      required:true,
      type:Array,
      default:[]
    },

    activeIndex:{
      type: Number,
      default: 0
    },
    //开启一级选择
    oneSelect: {
      type: Boolean,
      default: false,
    },
    //label展示字段
    labelName: {
      type: String,
      default: 'name'
    },
    //value选中字段
    valueName: {
      type: String,
      default: 'id'
    },
    // 是否禁止
    disabled:{
      type:Boolean,
      default:false
    },
    //初始选中值
    selectValue: {
      type: Array,
      default: () => {
        return [];
      }
    }
  })
  watch(() => [props.columns,props.selectValue],(val) => {
    hierarchyRef.value.getInitData(props.columns,props.selectValue,(data:any) => {
      pickerValue.value = data.names.join(';')
    })
  })
  onMounted(() => {
    hierarchyRef.value.getInitData(props.columns,props.selectValue,(data:any) => {
      pickerValue.value = data.names.join(';')
    })
  })
  const openPicker = () => {
    if(!props.disabled){
      hierarchyRef.value.show()
    }
  }
  const confirm  = (data:any) => {
    pickerValue.value = data.names.join(';')
    emit('update:modelValue',data.ids)
    emit('change',data)
  }
</script>

<template>
  <view class="select-picker">
    <view class="picker-value" :class="{placeholder:!pickerValue}">
      <view class="picker-text" @click="openPicker">{{ pickerValue ? pickerValue: placeholder }}</view>
      <view class="picker-close" v-if="!disabled">
        <up-icon name="arrow-right" color="#a6a5a5" size="14"></up-icon>
      </view>
    </view>
    <xx-hierarchy
      ref="hierarchyRef"
      :placeholder="placeholder"
      :changeTwoFun="changeTwoFun"
      :cascader-data="columns"
      :active-index="activeIndex"
      :one-select="oneSelect"
      :value-name="valueName"
      @confirm="confirm"
      :select-value="selectValue"
      :label-name="labelName"/>
  </view>
</template>

<style scoped lang="scss">
  .picker-value{
    background: #FFFFFF;
    border-radius: 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .picker-text{
      width: calc(100% - 24rpx);
      font-size: 28rpx;
    }
    &.placeholder{
      color: #a6a6a6;
    }
  }
</style>
